package com.garbagecode.resultbounds.dialect;

import org.apache.ibatis.session.RowBounds;

public class MySqlDialect implements Dialect {

  @Override
  public String getPaginationSql(String sql, int offset, int limit, String order) {
    if (sql == null) {
      throw new IllegalArgumentException("sql null");
    }

    StringBuffer buff = new StringBuffer(sql);
    
    // 排序
    if (order != null && order.trim().length() > 0) {
      buff.append(" ORDER BY ").append(order.replaceAll("\\.", " "));
    }

    // 分页
    if (offset != RowBounds.NO_ROW_OFFSET) {
      buff.append(" LIMIT ").append(offset);

      if (limit != RowBounds.NO_ROW_LIMIT) {
        buff.append(",").append(limit);
      } else {
        buff.append(",").append(Long.MAX_VALUE);
      }
    } else if (limit != RowBounds.NO_ROW_LIMIT) {
      buff.append(" LIMIT 0,").append(limit);
    }

    return buff.toString();
  }

  @Override
  public String getTotalCountSql(String sql) {
    if (sql == null) {
      throw new IllegalArgumentException("sql null");
    }

    int fromPos = sql.toLowerCase()
        .replaceAll("\\s", " ")
        .indexOf(" from ");

    if (fromPos < 0) {
      throw new RuntimeException("not found keyword 'from' in sql '" + sql + "'");
    }

    String totalCountSql = "SELECT COUNT(*) FROM " + sql.substring(fromPos + 6);

    return totalCountSql;
  }

}
